from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QTimer
from PyQt5.uic import loadUi
from src.utils.ui_utils import center_window
from src.utils.validators import validate_phone, validate_password

class RegisterView:
    """注册界面视图类"""
    
    def __init__(self, controller):
        # 保存控制器引用
        self.controller = controller
        
        # 加载UI文件
        self.ui = loadUi('src/ui/register.ui')
        
        # 连接按钮事件
        self.ui.registerButton.clicked.connect(self.on_register_clicked)
        self.ui.backToLoginButton.clicked.connect(self.on_back_clicked)
        
        # 设置窗口居中显示
        center_window(self.ui)
        
    def show(self):
        """显示注册界面"""
        self.ui.show()
        
    def hide(self):
        """隐藏注册界面"""
        self.ui.hide()
    def on_register_clicked(self):
        """注册按钮点击事件"""
        phone = self.ui.phoneInput.text().strip()
        password = self.ui.passwordInput.text().strip()
        confirm_password = self.ui.confirmPasswordInput.text().strip()
        
        # 验证输入
        if not phone:
            QMessageBox.warning(self.ui, '警告', '请输入手机号！')
            self.ui.phoneInput.setFocus()
            return
            
        # 验证手机号格式
        if not validate_phone(phone):
            QMessageBox.warning(self.ui, '警告', '请输入正确的手机号码！')
            self.ui.phoneInput.setFocus()
            return
            
        # 验证密码
        if not password:
            QMessageBox.warning(self.ui, '警告', '请设置密码！')
            self.ui.passwordInput.setFocus()
            return
            
        if not validate_password(password):
            QMessageBox.warning(self.ui, '警告', '密码长度应为6-20位！')
            self.ui.passwordInput.setFocus()
            return
            
        if password != confirm_password:
            QMessageBox.warning(self.ui, '警告', '两次输入的密码不一致！')
            self.ui.confirmPasswordInput.setFocus()
            return
            
        # 调用控制器处理注册逻辑
        self.controller.do_register(phone, password)
    
    def on_back_clicked(self):
        """返回登录按钮点击事件"""
        self.controller.show_login()
  
    
    def show_register_success(self):
        """显示注册成功消息"""
        QMessageBox.information(self.ui, '注册成功', '注册成功，请登录！')
        
    def show_register_error(self, message):
        """显示注册失败消息"""
        QMessageBox.critical(self.ui, '注册失败', message)